package com.wj.blog.service.impl;

import com.wj.blog.mapper.BlogMapper;
import com.wj.blog.pojo.Blog;
import com.wj.blog.utils.Page;
import com.wj.blog.vo.BlogVo;
import com.wj.blog.service.BlogService;
import com.wj.blog.service.TypeServcie;
import com.wj.blog.utils.IdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Author:   wj
 * Date:     2020/4/9 15:20
 * Description:
 */
@Service
public class BlogServiceImpl implements BlogService {
    @Autowired
    BlogMapper blogMapper;
    @Autowired
    IdWorker idWorker;
    @Autowired
    TypeServcie typeServcie;

    /**
     * 添加博客
     *
     * @param blog
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Blog blog){
        blog.setBlogId(idWorker.nextId()+"");
        blogMapper.save(blog);
    }

    @Override
    public void delete(String id) {
        blogMapper.delete(id);
    }

    /**
     * 更新博客
     *
     * @param blog
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Blog blog) {
        blogMapper.update(blog);
    }

    /**
     * 根据id查询阅读加一
     * 并查询文章的分类名
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BlogVo readId(String id) {
        //更新阅读数
        Blog blog = blogMapper.getById(id);
        blog.setBlogRead(blog.getBlogRead()+1);
        blogMapper.update(blog);
        //找到博客分类
        BlogVo blogVo = new BlogVo();
        String typeName = typeServcie.getById(blog.getBlogType()).getTypeName();
        blogVo.setTypeName(typeName);
        //将blog 转vo
        BeanUtils.copyProperties(blog,blogVo);
        return blogVo;
    }

    /**
     * 根据id 查询
     *
     * @return
     */
    @Override
    public Blog getById(String id) {
        return blogMapper.getById(id);
    }


    /**
     * 分页查询
     * 查询list 用于展示
     * 查询count 用于计算页数
     * @param page
     * @return
     */
    @Override
    public Page<BlogVo> getByPage(Page<BlogVo> page) {
        Page<BlogVo> pages = new Page<>();
        pages.setList(blogMapper.getByPage(page));
        pages.setTotalCount(blogMapper.getCount(page));
        return pages;
    }
}
